package aishua.com.mytestapplist.engin;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.ImageView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import aishua.com.mytestapplist.engin.impl.WebConnection;


public class ImageLoader {
	/** ͼƬ������� */
	private static Map<String, SoftReference<Drawable>> cacheMap;
	
	/** �̳߳ط��� */
	private static ExecutorService executorService;
	
	/** ������� */
	private static ImageLoader mImageCache = new ImageLoader();

	private String root_file;
	
	/** ����·�� */
	private final static String CACHE_PATH = "/imageCache";
	
	public static ImageLoader getIamgeLoader(){
		return mImageCache;
	}
	
	public interface ImageCallback {
		public void imageLoaded(Drawable imageDrawable, ImageView imageView);
		public void imageLoadedFailed(ImageView imageView);
	}
	
	public void loadDrawable(final ImageView imgView, final Context context,
							 final ImageCallback imageCallback) {
		root_file = imgView.getContext().getFilesDir().getAbsolutePath();
		final String url = (String) imgView.getTag();
		if (url == null) {
			return ;
		}
		final Handler handler = new Handler() {
			public void handleMessage(Message message) {
				if (message.what == 0) {
					imageCallback.imageLoaded((Drawable) message.obj, imgView);
				} else {
					imageCallback.imageLoadedFailed(imgView);
				}
			}
		};
		
		if(cacheMap == null) {
			cacheMap = new HashMap<String, SoftReference<Drawable>>();
		}
		
		if (cacheMap.containsKey(url)) {
			final SoftReference<Drawable> softReference = cacheMap.get(url);
			if (softReference.get() != null) {
				imageCallback.imageLoaded(softReference.get(), imgView);
				return ;
			}
		}
		
		if(isSDOK()) {
			File file = getSDFilePath(url);
			if(file.exists()){
				try {
					@SuppressWarnings("deprecation")
					Drawable drawable = new BitmapDrawable(BitmapFactory.decodeFile(file.toString()));
					if(drawable != null){
						cacheMap.put(url, new SoftReference<Drawable>(
								drawable));
						imageCallback.imageLoaded(drawable, imgView);
						return ;
					}
				
				} catch(Exception e){
					e.printStackTrace();
				}
			}
		}
		
		if (Looper.myLooper() == null) {
			Looper.prepare();
		}
		
		// ͼƬ�����̳߳ط���
		if(executorService == null){
			executorService = Executors.newFixedThreadPool(3);
		}
		executorService.submit(new Runnable() {
			public void run() {
				Drawable drawable_temp = loadImageFromUrl(url, context);
				if (drawable_temp != null) {
					cacheMap.put(url, new SoftReference<Drawable>(drawable_temp));
					Message message = handler.obtainMessage(0, drawable_temp);
					handler.sendMessage(message);
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});

	}
	
	
	/**
	 * �������ȡͼƬ
	 * @param imageUrl
	 * @return
	 */
	private Drawable loadImageFromUrl(String imageUrl, Context context) {
		try {
			WebConnection conn = new WebConnection(imageUrl);
			InputStream inStream = conn.executeHttpsGet(imageUrl);
			BitmapDrawable drawable = (BitmapDrawable) BitmapDrawable.createFromStream(inStream, "image");
			if (drawable != null) {
				savePic(drawable.getBitmap(), imageUrl);
			}
			return drawable;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private void savePic(Bitmap bitmap, String strFileName) {
		if(isSDOK()) {
			String filePath = isExistsFilePath();
			FileOutputStream fos = null;
			File file = new File(filePath, getSaveName(strFileName));
			if (!file.exists()) {
				try {
					fos = new FileOutputStream(file);
					if (null != fos) {
						bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
						fos.flush();
						fos.close();
					}
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
	
	private String getSaveName(String strFileName) {
		String url = null;
		url = strFileName.substring(strFileName.lastIndexOf("/")+1, strFileName.length());
		return url;
	}

	
	private String getSDPath(Context ctx) {
		File sdDir = null;
		try {
			if (isSDOK()) {
				sdDir = Environment.getExternalStorageDirectory();
			} else {
				return "";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sdDir.toString();
	}
	
	public boolean isSDOK() {
//		boolean sdCardExist = Environment.getExternalStorageState().equals(
//				android.os.Environment.MEDIA_MOUNTED); 
//		return sdCardExist;
		return true;
	}

	private String isExistsFilePath() {
		String filePath = root_file + CACHE_PATH;
		File file = new File(filePath);
		if (!file.exists()) {
			file.mkdirs();
		}
		return filePath;
	}
	
	private File getSDFilePath(String strFileName) {
		String filePath = isExistsFilePath();
		File file = new File(filePath, getSaveName(strFileName));
		return file;
	}
	
	public void deleteCache(Context context) {
		String filePath = context.getFilesDir().getAbsolutePath() + CACHE_PATH;
		File file = new File(filePath);
		delete(file);
	}
	
	private void delete(File file) {
    	
    	if (file.isFile()) {  
            file.delete();  
            return;  
    	}  
    	
    	if(file.isDirectory()){  
            File[] childFiles = file.listFiles();
            if (childFiles == null || childFiles.length == 0) {  
                file.delete();
                return;  
            }  
      
            for (int i = 0; i < childFiles.length; i++) {  
                delete(childFiles[i]);  
            }  
            file.delete();  
        }  
    } 
	
}
